import pygame as pg
import numpy as np
from PIL import Image, ImageSequence
from random import randint, choice
from interface import *
from function import *


LAWN_WIDTH = 80
LAWN_HEIGHT = 100
LAWN_ROW = 5
LAWN_COLUMN = 9
LAWN_START_X = 260
LAWN_START_Y = 82


def update(lawn_array):
    for row in range(lawn_array.shape[0]):
        for column in range(lawn_array.shape[1]):
            state = lawn_array[row][column]
            if isinstance(state, _Plant):
                state.update()


def onclick(lawn_array, mouse_pos):
    for row in range(lawn_array.shape[0]):
        for column in range(lawn_array.shape[1]):
            state = lawn_array[row][column]
            if isinstance(state, _Plant):
                state.onclick(mouse_pos)


class _Plant(GifObject):
    def __init__(self, screen, row, column, image_path: str = None, image_name: str = ''):
        super().__init__(screen, image_path, image_name)
        self.row = row
        self.column = column
        self.over = False
        self.coordinate = self.get_image_coordinate()

    def image_complete_path(self, image_name: str | list | tuple):
        if isinstance(image_name, str):
            return self.image_path + '\\' + image_name
        elif isinstance(image_name, (list, tuple)):
            return [self.image_path + '\\' + name for name in image_name]

    def get_image_coordinate(self):
        return LAWN_START_X + LAWN_WIDTH * self.column, LAWN_START_Y + LAWN_HEIGHT * self.row


class SunFlower(_Plant):
    def __init__(self, screen, row, column, random_sun: RandomSun):
        super().__init__(screen, row, column, image_path='images\\Plants\\SunFlower', image_name='SunFlower1.gif')
        self.random_sun = random_sun
        self.state2 = self.get_image_frames('SunFlower2.gif')
        self.production = randint(SUN_PRODUCTION[0], SUN_PRODUCTION[1])

    class FlowerSun(Sun):
        def __init__(self, screen, coordinate):
            super().__init__(screen)
            coordinate = (coordinate[0] + choice((-30, 30)), coordinate[1])
            self.trajectory = [(coordinate[0], coordinate[1] + y) for y in range(0, 40)]

    def update(self):
        if self.frames_number > self.production:
            state = self.state2
            if self.frames_number > self.production + randint(1, 3) * self.cycle:
                self.production = randint(SUN_PRODUCTION[0], SUN_PRODUCTION[1])
                state = self.state
                self.frames_number = self.frames_number % self.cycle
                self.random_sun.sun_list.append(self.FlowerSun(self.screen, self.coordinate))
        else:
            state = self.state
        self.screen.blit(state[self.frames_number % self.cycle], self.coordinate)
        self.frames_number += 1


